import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author dreamcatcher
 * @date 2022/5/4 15:35
 */
public class LayoutLoader {
    /**
     * 使用HashMap存放从.xml中加载的组件
     */
    private static HashMap<String, View> layoutMap = new HashMap<>();
    public static HashMap<String, View> getLayoutMap() {
        try {
            layoutLoader();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return layoutMap;
    }

    /**
     * layout加载方法，解析并加载.xml中的组件，使用反射创建对应的类
     * @throws Exception
     */
    private static void layoutLoader() throws Exception {
        File file = new File("layout/layout.xml");
        Document parse = parse(file);
        Iterator<Element> elementIterator = parse.getRootElement().elementIterator();

        while (elementIterator.hasNext()) {
            Element next = elementIterator.next();
            View view = ConvertElement2View(next);
            layoutMap.put(view.getId(),view);
        }
    }


    public static Document parse(File file) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        return document;
    }

    /**
     * 递归加载.xml中的组件，将其存放的HashMap中
     * @param next
     * @return
     * @throws Exception
     */
    private static View ConvertElement2View(Element next) throws Exception {
        //添加自身节点到hashmap中
        Class<?> aClass = Class.forName(next.getName());
        View v = (View) aClass.newInstance();
        String id = next.attributeValue("id");
        String text = next.attributeValue("text");
        String height = next.attributeValue("height");
        String weight = next.attributeValue("width");
        String clickable = next.attributeValue("clickable");

        v.setId(value(id));
        v.setText(value(text));
        v.setHeight(value(height));
        v.setWeight(value(weight));
        v.setClickAble(clickable == null?false:clickable.equals("true"));
        //添加子节点到hashmap中
        Iterator<Element> elementIterator = next.elementIterator();
        while (elementIterator.hasNext()) {
            Element child = elementIterator.next();
            View view = ConvertElement2View(child);
            layoutMap.put(view.getId(),view);
        }

        return v;
    }


    private static String value(String v) {
        return v == null ? "" : v;
    }

}
